"""
项目模型
"""

from datetime import datetime
from app import db


class Project(db.Model):
    """项目模型"""
    __tablename__ = 'projects'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(200), nullable=False)
    description = db.Column(db.Text, nullable=True)
    
    # 外键
    owner_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    team_id = db.Column(db.Integer, db.ForeignKey('teams.id'), nullable=True)
    
    # 时间字段
    created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    start_date = db.Column(db.DateTime, nullable=True)
    end_date = db.Column(db.DateTime, nullable=True)
    
    # 项目状态
    is_active = db.Column(db.Boolean, default=True, nullable=False)
    is_archived = db.Column(db.Boolean, default=False, nullable=False)
    
    # 关系
    tasks = db.relationship('Task', backref='project', lazy='dynamic', cascade='all, delete-orphan')
    
    def __repr__(self):
        return f'<Project {self.name}>'
    
    def to_dict(self):
        """转换为字典"""
        try:
            return {
                'id': self.id,
                'name': self.name,
                'description': self.description,
                'owner_id': self.owner_id,
                'team_id': self.team_id,
                'created_at': self.created_at.isoformat() if self.created_at else None,
                'updated_at': self.updated_at.isoformat() if self.updated_at else None,
                'start_date': self.start_date.isoformat() if self.start_date else None,
                'end_date': self.end_date.isoformat() if self.end_date else None,
                'is_active': self.is_active,
                'is_archived': self.is_archived,
                'owner': self.owner.to_dict() if hasattr(self, 'owner') and self.owner else None,
                'team': self.team.to_dict() if hasattr(self, 'team') and self.team else None,
                'task_count': self.tasks.count() if hasattr(self, 'tasks') else 0,
                'completed_tasks': self.tasks.filter_by(status='done').count() if hasattr(self, 'tasks') else 0
            }
        except Exception as e:
            # 如果关系对象访问失败，返回基本信息
            return {
                'id': self.id,
                'name': self.name,
                'description': self.description,
                'owner_id': self.owner_id,
                'team_id': self.team_id,
                'created_at': self.created_at.isoformat() if self.created_at else None,
                'updated_at': self.updated_at.isoformat() if self.updated_at else None,
                'start_date': self.start_date.isoformat() if self.start_date else None,
                'end_date': self.end_date.isoformat() if self.end_date else None,
                'is_active': self.is_active,
                'is_archived': self.is_archived,
                'task_count': 0,
                'completed_tasks': 0
            }
    
    def get_progress_percentage(self):
        """获取项目进度百分比"""
        total_tasks = self.tasks.count()
        if total_tasks == 0:
            return 0
        
        completed_tasks = self.tasks.filter_by(status='done').count()
        return round((completed_tasks / total_tasks) * 100, 2)
    
    def get_overdue_tasks(self):
        """获取项目中的过期任务"""
        return self.tasks.filter(
            Task.due_date < datetime.utcnow(),
            Task.status != 'done'
        ).all()
    
    def archive(self):
        """归档项目"""
        self.is_archived = True
        self.is_active = False
        db.session.commit()
    
    def activate(self):
        """激活项目"""
        self.is_archived = False
        self.is_active = True
        db.session.commit()
    
    @classmethod
    def get_active_projects(cls):
        """获取活跃项目"""
        return cls.query.filter_by(is_active=True, is_archived=False).all()
    
    @classmethod
    def get_by_owner(cls, owner_id):
        """获取指定用户的项目"""
        return cls.query.filter_by(owner_id=owner_id).all()
    
    @classmethod
    def get_by_team(cls, team_id):
        """获取指定团队的项目"""
        return cls.query.filter_by(team_id=team_id).all()
    
    @classmethod
    def find_by_id(cls, project_id):
        """根据ID查找项目"""
        return cls.query.get(project_id)
    
    @classmethod
    def get_user_projects(cls, user_id):
        """获取用户相关的项目"""
        from app.models.team import TeamMember
        # 获取用户拥有的项目
        owned_projects = cls.query.filter_by(owner_id=user_id).all()
        
        # 获取用户团队的项目
        team_projects = cls.query.join(TeamMember, cls.team_id == TeamMember.team_id).filter(
            TeamMember.user_id == user_id
        ).all()
        
        # 合并并去重（使用ID去重）
        all_projects = owned_projects + team_projects
        seen_ids = set()
        unique_projects = []
        for project in all_projects:
            if project.id not in seen_ids:
                seen_ids.add(project.id)
                unique_projects.append(project)
        
        return unique_projects
    
    def can_access(self, user_id):
        """检查用户是否可以访问项目"""
        # 项目所有者可以访问
        if self.owner_id == user_id:
            return True
        
        # 团队成员可以访问
        if self.team_id:
            from app.models.team import TeamMember
            member = TeamMember.query.filter_by(
                team_id=self.team_id, 
                user_id=user_id
            ).first()
            if member:
                return True
        
        return False
    
    def get_tasks(self):
        """获取项目任务"""
        return self.tasks.all()
    
    def get_stats(self):
        """获取项目统计信息"""
        tasks = self.tasks.all()
        total_tasks = len(tasks)
        completed_tasks = len([t for t in tasks if t.status.value == 'done'])
        
        return {
            'total_tasks': total_tasks,
            'completed_tasks': completed_tasks,
            'completion_rate': (completed_tasks / total_tasks * 100) if total_tasks > 0 else 0,
            'active_tasks': len([t for t in tasks if t.status.value in ['todo', 'in_progress', 'review']])
        }